<template>
  <div class="fill">
    <div class="table">
      <el-table
        v-loading="data.dictionaryTypesLoading"
        element-loading-text="数据加载中..."
        empty-text="暂无数据"
        class="fill"
        :row-key="(row:any)=>row.id"
        stripe
        :data="data.dictionaryTypes"
        @row-click="events.handleRowClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          show-overflow-tooltip
          fixed
          prop="name"
          width="150"
          label="名称"
        />
        <el-table-column
          show-overflow-tooltip
          prop="key"
          width="200"
          label="键值"
        >
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="description"
          label="描述"
        />
        <el-table-column prop="subCount" width="100" label="子级数" />
        <el-table-column
          show-overflow-tooltip
          prop="authName"
          width="150"
          label="作者"
        />
        <el-table-column prop="createTime" width="200" label="创建时间" />
      </el-table>
    </div>
    <div class="pagination">
      <el-pagination
        background
        v-model:page-size="data.pagination.limit"
        v-model:current-page="data.pagination.page"
        :page-size-options="[10, 20, 30, 40, 50]"
        layout="prev, pager, next, jumper,sizes"
        :total="data.total"
      />
    </div>
    <div>
      <el-drawer
        v-model="data.showUpdate"
        style="background-color: #e6eefa"
        size="60%"
        class="high-z-index-drawer"
        :before-close="events.drawerBeforeClose"
      >
        <template #header>
          <span class="drawer-title">字典类型详情</span>
        </template>
        <el-scrollbar class="particular-vip">
          <div class="homes">
            <label>{{ data.dictionaryType.name }}</label>
            <div style="float: right; margin: 4px 4px 4px 16px">
              <template v-if="data.isUpdate">
                <el-button
                  :disabled="
                    JSON.stringify(data.updateDictionaryType) ===
                    JSON.stringify(data.dictionaryType)
                  "
                  type="success"
                  @click="events.updateDictionaryType"
                  >保存</el-button
                >
                <el-button type="info" @click="events.hideUpdateDictionaryType"
                  >取消</el-button
                >
              </template>
              <template v-else>
                <el-button
                  type="warning"
                  @click="events.showUpdateDictionaryType"
                >
                  编辑
                </el-button>
              </template>
            </div>
            <div style="float: right; margin: 4px 4px 4px 16px">
              <el-button type="primary" @click="events.openCreateDictionary"
                >添加子级</el-button
              >
            </div>
            <div class="bq" @click="events.delDictionaryType()">
              <i class="iconfont icon-shanchu"></i>
            </div>
          </div>
          <div class="infos">
            <el-descriptions label-width="150px" :column="2" border
              ><el-descriptions-item label="名称">{{
                data.dictionaryType.name
              }}</el-descriptions-item>
              <el-descriptions-item label="键值">
                <template v-if="data.isUpdate">
                  <el-input v-model="data.updateDictionaryType.key" />
                </template>
                <template v-else>
                  {{ data.dictionaryType.key }}
                </template>
              </el-descriptions-item>
              <el-descriptions-item label="描述" :span="2">
                <template v-if="data.isUpdate">
                  <el-input v-model="data.updateDictionaryType.description" />
                </template>
                <template v-else>
                  {{ data.dictionaryType.description }}
                </template>
              </el-descriptions-item>
              <el-descriptions-item label="作者">
                {{ data.dictionaryType.authName }}
              </el-descriptions-item>
              <el-descriptions-item label="创建日期">
                {{ data.dictionaryType.createTime }}
              </el-descriptions-item>
            </el-descriptions>
          </div>
          <div class="add-sub">
            <template v-if="data.curentDictionary">
              <div>{{ data.curentDictionary.value }}</div>
              <div class="add-sub-btn">
                <el-button type="info" @click="events.back">返回</el-button>
                <el-button type="primary" @click="events.openCreateDictionary2"
                  >添加</el-button
                >
              </div>
            </template>
          </div>
          <div>
            <el-table
              v-loading="data.dictionarysLoading"
              element-loading-text="数据加载中..."
              empty-text="暂无数据"
              :row-key="(row:any)=>row.id"
              stripe
              border
              :data="data.dictionarys"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column fixed prop="value" label="值" />
              <el-table-column prop="subCount" label="子级数"></el-table-column>
              <el-table-column prop="createTime" label="创建时间" sortable />
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button
                    type="primary"
                    @click="events.detailDictionary(scope.row)"
                    >详情</el-button
                  >
                  <el-button
                    type="danger"
                    @click="events.delDictionary(scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-scrollbar>
      </el-drawer>
    </div>
    <div>
      <el-dialog
        v-model="data.showCreateDictionary"
        title="添加字典"
        width="500"
        :before-close="events.closeCreateDictionary"
      >
        <el-form
          ref="createDictionaryTypeFormRef"
          :model="data.createDictionary"
          :rules="data.createDictionaryFormRules"
          label-width="60px"
        >
          <el-form-item label="键值" prop="value">
            <el-input
              v-model="data.createDictionary.value"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item>
            <div class="right-box">
              <el-button type="primary" @click="events.createDictionary">
                提交
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        v-model="data.showCreateDictionary2"
        title="添加字典"
        width="500"
        :before-close="events.closeCreateDictionary2"
      >
        <el-form
          ref="createDictionaryTypeFormRef"
          :model="data.createDictionary2"
          :rules="data.createDictionaryFormRules"
          label-width="60px"
        >
          <el-form-item label="键值" prop="value">
            <el-input
              v-model="data.createDictionary2.value"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item>
            <div class="right-box">
              <el-button type="primary" @click="events.createDictionary2"
                >提交</el-button
              >
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  addDictionary,
  deleteDictionary,
  detailDictionary,
  getDictionaryListByDictionaryTypeKey,
  getDictionaryListByParentId,
} from "@/api/dictionary";
import {
  deleteDictionaryType,
  getDictionaryTypePagination,
  updateDictionaryType,
} from "@/api/dictionaryType";
import { confirmBox, toast } from "@/tools/tools";
import { onMounted, reactive, watch } from "vue";

const props = defineProps({
  searchWord: {
    type: String,
  },
  flag: {
    type: Boolean,
  },
});

interface Data {
  createDictionary2: any;
  showCreateDictionary2: boolean;
  curentDictionary: any;
  dictionaryTypes: any[];
  dictionaryTypesLoading: boolean;
  pagination: {
    page: number;
    limit: number;
  };
  total: number;
  isUpdate: boolean;
  showUpdate: boolean;
  dictionaryType: any;
  updateDictionaryType: any;
  dictionarys: any[];
  dictionarysLoading: boolean;
  createDictionary: any;
  createDictionaryFormRules: any;
  showCreateDictionary: boolean;
}

const data = reactive<Data>({
  createDictionary2: {},
  showCreateDictionary2: false,
  curentDictionary: null,
  dictionaryTypes: [],
  dictionaryTypesLoading: false,
  pagination: {
    page: 1,
    limit: 10,
  },
  total: 0,
  showUpdate: false,
  isUpdate: false,
  dictionaryType: {},
  updateDictionaryType: {},
  dictionarys: [],
  dictionarysLoading: false,
  createDictionary: {},
  createDictionaryFormRules: {
    value: [{ required: true, message: "请输入键值" }],
  },
  showCreateDictionary: false,
});
const methods = {
  async bindDictionaryTypes() {
    data.dictionaryTypesLoading = true;
    const res = await getDictionaryTypePagination({
      ...data.pagination,
      key: props.searchWord,
    });
    if (res.code >= 0) {
      data.dictionaryTypes = res.data.data.map((d: any) => {
        d.createTime = new Date(d.createTime).toLocaleString();
        return d;
      });
      data.total = res.data.total;
    }
    data.dictionaryTypesLoading = false;
  },
  async bindDictionarys() {
    data.dictionarysLoading = true;
    const res = await getDictionaryListByDictionaryTypeKey(
      data.dictionaryType.key
    );
    if (res.code >= 0) {
      data.dictionarys = res.data.map((d: any) => {
        d.createTime = new Date(d.createTime).toLocaleString();
        return d;
      });
    }
    data.dictionarysLoading = false;
  },
};

const events = {
  async drawerBeforeClose(done: Function) {
    data.curentDictionary = null;
    done(false);
  },
  async back() {
    if (data.curentDictionary.parentId == null) {
      data.curentDictionary = null;
      await methods.bindDictionarys();
    } else {
      const res = await detailDictionary(data.curentDictionary.parentId);
      console.log(res);
      if (res.code >= 0) {
        data.curentDictionary = res.data;
        await events.detailDictionary(data.curentDictionary);
      }
    }
  },
  handleRowClick(row: any) {
    data.showUpdate = true;
    data.dictionaryType = JSON.parse(JSON.stringify(row));
    methods.bindDictionarys();
  },
  showUpdateDictionaryType() {
    data.updateDictionaryType = JSON.parse(JSON.stringify(data.dictionaryType));
    data.isUpdate = true;
  },
  hideUpdateDictionaryType() {
    data.isUpdate = false;
  },
  async updateDictionaryType() {
    const res = await updateDictionaryType(data.updateDictionaryType);
    if (res.code >= 0) {
      data.isUpdate = false;
      data.dictionaryType = data.updateDictionaryType;
      methods.bindDictionaryTypes();
      toast.success(res.message || "修改成功");
    } else {
      toast.error(res.message || "修改失败");
    }
  },
  openCreateDictionary() {
    data.showCreateDictionary = true;
  },
  closeCreateDictionary() {
    data.showCreateDictionary = false;
  },
  async detailDictionary(row: any) {
    data.dictionarysLoading = true;
    const res = await getDictionaryListByParentId(row.id);
    data.dictionarysLoading = false;
    if (res.code >= 0) {
      data.dictionarys = res.data;
      data.curentDictionary = row;
    }
  },
  async createDictionary() {
    const res = await addDictionary({
      ...data.createDictionary,
      dictionaryTypeId: data.dictionaryType.id,
    });
    if (res.code >= 0) {
      data.showCreateDictionary = false;
      data.createDictionary = {};
      methods.bindDictionarys();
      methods.bindDictionaryTypes();
      toast.success(res.message || "添加成功");
    } else {
      toast.error(res.message || "添加失败");
    }
  },
  openCreateDictionary2() {
    data.showCreateDictionary2 = true;
  },
  closeCreateDictionary2() {
    data.showCreateDictionary2 = false;
  },
  async createDictionary2() {
    const res = await addDictionary({
      ...data.createDictionary2,
      dictionaryTypeId: data.dictionaryType.id,
      parentId: data.curentDictionary.id,
    });
    if (res.code >= 0) {
      data.showCreateDictionary2 = false;
      data.createDictionary2 = {};
      events.detailDictionary(data.curentDictionary);
      methods.bindDictionaryTypes();
      toast.success(res.message || "添加成功");
    } else {
      toast.error(res.message || "添加失败");
    }
  },
  async delDictionaryType() {
    confirmBox(
      `确认删除字典类别“${data.dictionaryType.name}”吗？`,
      async () => {
        const res = await deleteDictionaryType(data.dictionaryType.id);
        if (res.code >= 0) {
          data.showUpdate = false;
          data.dictionaryType = {};
          methods.bindDictionaryTypes();
          toast.success(res.message || "删除成功");
        } else {
          toast.error(res.message || "删除失败");
        }
      }
    );
  },
  async delDictionary(row: any) {
    confirmBox(`确认删除字典“${row.value}”吗？`, async () => {
      const res = await deleteDictionary(row.id);
      if (res.code >= 0) {
        methods.bindDictionarys();
        methods.bindDictionaryTypes();
        toast.success(res.message || "删除成功");
      } else {
        toast.error(res.message || "删除失败");
      }
    });
  },
};

watch([data.pagination, () => props.searchWord, () => props.flag], async () => {
  methods.bindDictionaryTypes();
});

onMounted(async () => {
  methods.bindDictionaryTypes();
});
</script>

<style scoped>
.particular-vip {
  width: calc(100% - 16px);
  height: calc(100% - 16px);
  padding: 10px 16px 14px 14px;
  background-color: #fff;
  border-radius: 10px;
  overflow: auto;
}
.homes {
  height: 56px;
  margin-bottom: 8px;
}
.homes label {
  font-size: 25px;
}
.bq {
  height: 35px;
  width: 35px;
  background-color: #f5f5f5;
  border-radius: 6px;
  margin: 4px;
  float: right;
  text-align: center;
  cursor: pointer;
}
.bq:hover {
  background-color: #e6e6e6;
}
.infos {
  margin-bottom: 8px;
}
.add-sub {
  display: flex;
  margin-bottom: 8px;
}
.add-sub-btn {
  margin-left: auto;
}
.drawer-title {
  font-size: 20px;
  font-weight: bold;
}
</style>
